<template>
  <div>
    <h2>商品列表</h2>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/MemberMain">主页</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 20px;">
      <el-table :data="goodsList" style="width: 100%;" v-loading="loading" empty-text="暂无商品信息">
        <el-table-column prop="goodsName" label="商品名称" />
        <el-table-column prop="goodsPrice" label="价格(元)" />
        <el-table-column prop="goodsType" label="类型" />
        <el-table-column label="图片">
          <template #default="scope">
            <el-image :src="scope.row.goodsImage" style="width: 80px; height: 80px;" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="goodsInventory" label="库存" />
        <el-table-column label="购买数量">
          <template #default="scope">
            <el-input-number v-model="scope.row.buyCount" :min="1" :max="scope.row.goodsStock" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="addToCart(scope.row)">加入购物车</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const goodsList = ref([])
const loading = ref(false)

const loadData = () => {
  loading.value = true
  axios.get('/server/goods/search', {
    params: { page: 1, size: 10 }
  })
      .then(response => {
        if (response.data.code === 200) {
          goodsList.value = response.data.data.records.map(item => ({
            ...item,
            goodsImage: item.goodsImages, // 从后端字段中拷贝完整签名URL
            buyCount: 1 // 初始化购买数量
          }))
        } else {
          ElMessage.error('获取数据失败: ' + (response.data.message || '未知错误'))
        }
      })
      .catch(() => {
        ElMessage.error('请求出错，无法加载数据')
      })
      .finally(() => {
        loading.value = false
      })
}

onMounted(() => {
  loadData()
})

const addToCart = (item) => {
  const mount = item.buyCount
  if (mount > item.goodsIventory) {
    ElMessage.error('购买数量超过库存')
    return
  }

  axios.post('/server/cart/add',new URLSearchParams({
    goodsId: item.gid,
    mount: mount
  }),{
    headers: {
      'Authorization':  localStorage.getItem('token')
    }
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success(`已将 ${item.goodsName} ×${mount} 加入购物车`)
    } else {
      ElMessage.error('加入购物车失败: ' + (res.data.message || '未知错误'))
    }
  }).catch(() => {
    ElMessage.error('请求失败，加入购物车出错')
  })
}
</script>

<style scoped>
h2 {
  margin-bottom: 10px;
}
</style>
